﻿using System;
using System.Web.SessionState;
using System.Collections.Generic;
using System.Xml;
using System.Text;
using System.Web;
using shop;
using shop.cart;

namespace comix
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>

    public class addToCartAjax : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {

            StringBuilder sb = new StringBuilder();
            XmlWriter xw = XmlWriter.Create(sb);
            xw.WriteStartElement("result");
            int id = Convert.ToInt32(context.Request.Form["id"]);
            context.Response.ContentType = "text/xml";
            if (id > 0)
            {
                Cart c = (Cart)context.Session["cart"];
                bool exists = false;
                xw.WriteStartElement("cartItem");
                foreach (CartItem cci in c.Items)
                {
                    
                    if (cci.Item.ItemId() == id)
                    {                        
                        xw.WriteAttributeString("id", "-1");    
                        xw.WriteEndElement();
                        exists = true;
                        break;
                    }
                }
               if(!exists)
                {
                CartItem ci = new CartItem();
                Book b = new Book();
                b.Id = id;
                b.FillItem();
                ci.Item = b;
                ci.Quantity = 1;
                c.Add(ci);      
                xw.WriteAttributeString("id", id.ToString());
                xw.WriteAttributeString("price", b.Price.ToString());
                xw.WriteAttributeString("desc", b.Title);
                xw.WriteAttributeString("total", c.TotalPrice().ToString());
                xw.WriteEndElement();
               // context.Response.Write(id.ToString() + ":" + b.Price.ToString()+"|"+c.TotalPrice().ToString());
                }
            }
            xw.WriteEndElement();
            xw.Close();
            context.Response.Write(sb.ToString());
            

            
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
